package com.zb.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.junit.Test;


public class DatagramSocketDemo {
    /**
     * send发送
     */
    @Test
    public void send() throws IOException, InterruptedException {
        // 打开DatagramChannel
        DatagramChannel sdc = DatagramChannel.open();

        // 目的地址
        InetSocketAddress ads = new InetSocketAddress("127.0.0.1", 10086);

        // 循环发送
        while (true) {
            String s = "测试abc" + System.currentTimeMillis();
            // 缓冲区
            ByteBuffer buf = ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8));
            // 发送
            sdc.send(buf, ads);

            System.out.println(s + "发送完毕！");
            Thread.sleep(2000);
        }
    }

    /**
     * receive接收
     */
    @Test
    public void receive() throws IOException {
        // 打开DatagramChannel
        DatagramChannel rdc = DatagramChannel.open();

        // 接收端口
        InetSocketAddress ads = new InetSocketAddress(10086);

        // 绑定端口
        rdc.bind(ads);

        // 缓冲区
        ByteBuffer buf = ByteBuffer.allocate(30);

        // 循环接收
        while (true) {
            // 清空缓冲区
            buf.clear();
            // 接收
            SocketAddress sa = rdc.receive(buf);
            // 缓冲区读写反转
            buf.flip();

            System.out.println(sa.toString());
            System.out.println(Charset.forName("utf8").decode(buf));
        }
    }

    /**
     * write、read、connect
     */
    @Test
    public void connect() throws IOException {
        // 打开DatagramChannel
        DatagramChannel rdc = DatagramChannel.open();

        // 定义接收端口
        InetSocketAddress ads = new InetSocketAddress(9999);

        // 绑定端口
        rdc.bind(ads);

        rdc.connect(new InetSocketAddress("127.0.0.1", 9999));

        // 发送
        String s = "abc测试" + System.currentTimeMillis();
        // 缓冲区
        ByteBuffer buf1 = ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8));
        // 发送
        rdc.write(buf1);
        System.out.println(s + "发送完毕！");

        // 接收
        // 缓冲区
        ByteBuffer buf = ByteBuffer.allocate(128);
        // 循环接收
        while(true){
            // 清空缓冲区
            buf.clear();
            // 读取
            rdc.read(buf);
            // 读写反转
            buf.flip();

            System.out.println(rdc.getRemoteAddress());
            System.out.println(Charset.forName("utf8").decode(buf));
        }
    }
}
